package com.shuoyue.ycgk.ui.account.login;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.shuoyue.appdepends.commonutils.ActivityTaskManager;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.baseadapter.IndexFragmentAdapter;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.account.AccountContract;
import com.shuoyue.ycgk.ui.account.BindPhoneActivity;
import com.shuoyue.ycgk.ui.main.MainTabActivity;
import com.shuoyue.ycgk.umeng.onkeyloginconfig.AuthPageConfig;
import com.shuoyue.ycgk.umeng.onkeyloginconfig.BaseUIConfig;
import com.shuoyue.ycgk.umeng.uitls.ExecutorManager;
import com.shuoyue.ycgk.utils.DevicesUtil;
import com.shuoyue.ycgk.utils.SimpleCodeUtil;
import com.shuoyue.ycgk.utils.XToast;
import com.umeng.umverify.UMResultCode;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.shuoyue.ycgk.umeng.uitls.MockRequest.getPhoneNumber;

public class LoginActivity extends BaseMvpActivity implements AccountContract.View {
    @BindView(R.id.viewPager)
    ViewPager viewPager;

    List<BaseMvpFragment> fragmentList = new ArrayList<>();
    FragmentAccountLogin fragmentAccountLogin;
    FragmentSmsLogin fragmentSmsLogin;
    IndexFragmentAdapter adapter;

    private UMVerifyHelper mPhoneNumberAuthHelper;
    private UMTokenResultListener mTokenResultListener;
    private AuthPageConfig mUIConfig;

    AccountContract.Presenter accountPresenter;
    static int srequestCode = -1;
    public final static int REQUEST_CODE = 1543;
    @BindView(R.id.smscode)
    TextView smscode;
    @BindView(R.id.pwd)
    TextView pwd;
    @BindView(R.id.wechat)
    TextView wechat;


    public static void start(Context context) {
//        context.startActivity(new Intent(context, LoginActivity.class));
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);//注意本行的FLAG设置 
        context.startActivity(intent);
    }


    public static void startForResult(Activity context) {
        context.startActivityForResult(new Intent(context, LoginActivity.class).putExtra("srequestCode", REQUEST_CODE),
                REQUEST_CODE);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activityl_ogin_main;
    }

    @Override
    protected void initView() {
//        UserInfo userInfo = SPUtils.getUserInfo(mContext);
//        if (userInfo != null) {
//            MemeryCatch.token = userInfo.getToken();
//            startActivity(new Intent(mContext, MainTabActivity.class));
//            finish();
//        }
        fragmentAccountLogin = new FragmentAccountLogin();
        fragmentSmsLogin = new FragmentSmsLogin();
        fragmentList.add(fragmentSmsLogin);
        fragmentList.add(fragmentAccountLogin);
        adapter = new IndexFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    smscode.setVisibility(View.GONE);
                    pwd.setVisibility(View.VISIBLE);
                } else if (position == 1) {
                    pwd.setVisibility(View.GONE);
                    smscode.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void initData() {
        srequestCode = getIntent().getIntExtra("srequestCode", -1);
        accountPresenter = new AccountContract.Presenter();
        accountPresenter.attachView(this);

        sdkInit();
        mUIConfig = BaseUIConfig.init(this, mPhoneNumberAuthHelper);
//        oneKeyLogin();

    }


    @OnClick({R.id.wechat, R.id.back, R.id.smscode, R.id.pwd, R.id.onekeyLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.wechat:
                WeChatLogin.login(this, (openId, accesstoken) -> {
                    String deviceName = null, imei = null;
//                    if (EasyPermissions.hasPermissions(mContext, Manifest.permission.READ_PHONE_STATE)) {
//                        deviceName = DevicesUtil.getManuFacturer() + DevicesUtil.getModel();
//                        imei = SimpleCodeUtil.getSimpleDeviceCode(mContext);
//                        if (TextUtils.isEmpty(imei)) {
//                            UUID uuid = UUID.randomUUID();
//                            imei = uuid.toString();
//                            SimpleCodeUtil.writeSimpleDeviceCode(mContext,imei);
//                        }
//                    } else {
//                        EasyPermissions.requestPermissions(this, "设备信息权限",
//                                109, Manifest.permission.READ_PHONE_STATE);
//                        toast("请打开获取手机信息权限");
//                        return;
//                    }
                    deviceName = DevicesUtil.getManuFacturer() + DevicesUtil.getModel();
                    imei = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                    if (TextUtils.isEmpty(imei)) {
                        imei = deviceName;
                    }
                    accountPresenter.wechatLogin(openId, accesstoken, imei, deviceName);
                });
                break;
            case R.id.back:
//                ActivityTaskManager.getInstance().closeAllActivity();
//                android.os.Process.killProcess(android.os.Process.myPid());   //获取PID
//                System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
                finish();
            case R.id.smscode:
                viewPager.setCurrentItem(0);
                smscode.setVisibility(View.GONE);
                pwd.setVisibility(View.VISIBLE);
                break;
            case R.id.pwd:
                viewPager.setCurrentItem(1);
                pwd.setVisibility(View.GONE);
                smscode.setVisibility(View.VISIBLE);
                break;
            case R.id.onekeyLogin:
                oneKeyLogin();
                break;
        }
    }

    @Override
    public void loginSuc(UserInfo userInfo) {
        if (userInfo != null) {
            MemeryCatch.token = userInfo.getToken();
            SPUtils.updateUserInfo(mContext, userInfo);
            if (srequestCode == -1) {
                startActivity(new Intent(mContext, MainTabActivity.class));
                finish();
            } else {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    public void registSuc() {

    }

    @Override
    public void registFail(String msg) {

    }

    @Override
    public void resetSuc() {

    }

    @Override
    public void bindPhone(String openId, String accessToken) {
        BindPhoneActivity.start(this, openId, accessToken);
    }

    @Override
    public void onBackPressed() {
        ActivityTaskManager.getInstance().closeAllActivity();
    }

    public void sdkInit() {
        mTokenResultListener = new UMTokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                UMTokenRet tokenRet = null;
                try {
                    tokenRet = UMTokenRet.fromJson(s);
                    if (UMResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("TAG1", "唤起授权页成功：" + s);
                    }

                    if (UMResultCode.CODE_GET_TOKEN_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("TAG2", "获取token成功：" + s);
                        getResultWithToken(tokenRet.getToken());
                        mUIConfig.release();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
                Log.e("onekeyLogin", "获取token失败：" + s);
                UMTokenRet tokenRet = null;
                mPhoneNumberAuthHelper.quitLoginPage();
                try {
                    tokenRet = UMTokenRet.fromJson(s);
                    XToast.toast(mContext, tokenRet.getMsg());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mUIConfig.release();
            }
        };
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(this, mTokenResultListener);
        mPhoneNumberAuthHelper.setAuthSDKInfo("8Ihtq4hXDTKs5vmt3h1K4yBbfUKirqUPH6CvhAQJLTtpqnjIgnfKELrbw+SyLc98kHPKrBfMS7HwYkWLo9PEqBaSzDwlJiPZZGVSp+Vat1XaZwuUGtOI+0u65WBN9FjxRwRaRoU0R1MOZ3c0E7pQS/1gerw9YiRDC46Rk1whPQ9pr6wlnxz5qHU2mRLKaRBErbdC0DBA/2/aJh/IRhpswvzr23VNkwhlFMXfvie67ZrzI3h/OEIUP9u6J4pyjM+ZKbPWXSwRHz8NcK4jBfdfRIpBfB4yFBaSk7Ws9oNrJt2OxXjuXbzZ8g==");
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private void oneKeyLogin() {
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(getApplicationContext(), mTokenResultListener);
        mUIConfig.configAuthPage();
        getLoginToken(5000);
    }

    /**
     * 拉起授权页
     *
     * @param timeout 超时时间
     */
    public void getLoginToken(int timeout) {
        mPhoneNumberAuthHelper.getLoginToken(this, timeout);
    }


    public void getResultWithToken(final String token) {
        ExecutorManager.run(() -> {
            final String result = getPhoneNumber(token);
            LoginActivity.this.runOnUiThread(() -> {
//                        mTvResult.setText("登陆成功：" + result);
                accountPresenter.oneKeyLogin(token);
                mPhoneNumberAuthHelper.quitLoginPage();
            });
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUIConfig.onResume();
    }

}
